/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tela;

import ferramentas.CFG;
import ferramentas.Query;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author carlo
 */
public class removerDocumento extends HttpServlet {

    private static final String TMP_DIR_PATH = System.getProperty("java.io.tmpdir");
    private File tmpDir = new File(TMP_DIR_PATH);
    private int MAX_SIZE_UPLOAD = 20 * 1024 * 1024; // 5Mb
    private String ENCODING = "UTF-8";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            int curso = Integer.parseInt(request.getParameter("curso"));
            int idDocumento = Integer.parseInt(request.getParameter("id"));
            Query q = new Query();
            q.removerDocumento(idDocumento, curso);
            out.println("<script>window.alert('Documento excluído!');location.href='index.jsp?conteudo=aprovados&curso=" + curso + "';</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            out.println("<script>window.alert('Operação não realizada!')</script>");
        } finally {
            out.close();
        }
    }

    private ServletFileUpload getHandler() throws FileUploadException {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        //fileItemFactory.setSizeThreshold(MAX_SIZE_UPLOAD);
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        uploadHandler.setHeaderEncoding(ENCODING);
        uploadHandler.setFileSizeMax(MAX_SIZE_UPLOAD);

        return uploadHandler;
    }

    private List getItemsRequest(HttpServletRequest request, ServletFileUpload uploadHandler) throws FileUploadException {
        return uploadHandler.parseRequest(request);
    }

    private String getParameter(String fieldName, List items) throws UnsupportedEncodingException {
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase(fieldName)) {
                    return new String(item.getString().getBytes("iso-8859-1"), "UTF-8");
                }
            }
        }
        return null;
    }

    private FileItem getFile(String fieldName, List items) {
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase(fieldName)) {
                    return item;
                }
            }
        }
        return null;
    }

    private String getEnderecoRelativoDocumentos(HttpServletRequest request) {
        String schema = request.getScheme();
        String porta = request.getServerPort() != 0 ? ":" + request.getServerPort() : "";
        String servidor = request.getServerName();
        String endereco_servidor = schema + "://" + servidor + porta + "/";
        return endereco_servidor + CFG.DIRETORIO_ARQUIVOS + "/" + CFG.DIRETORIO_DOCUMENTOS + "/";
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String getPastaDocumentos() {
        String root = getServletContext().getRealPath("/");
        String localDocumentos = root.substring(0, root.lastIndexOf(getServletContext().getContextPath().replace("/", System.getProperty("file.separator"))))
                + System.getProperty("file.separator") + CFG.DIRETORIO_ARQUIVOS
                + System.getProperty("file.separator") + CFG.DIRETORIO_DOCUMENTOS;
        return localDocumentos + System.getProperty("file.separator");
    }
}
